#include "mytcpserver.h"
#include "mytcpsocket.h"

MyTcpServer &MyTcpServer::getInstance()
{
    static MyTcpServer instance;
    return instance;
}

void MyTcpServer::incomingConnection(qintptr handle)
{
    qDebug() << "新的客户端连接";
    // 每一个新的客户端连接都其tcpSocket将存入的列表中
    MyTcpSocket* pTcpSocket = new MyTcpSocket;
    pTcpSocket->setSocketDescriptor(handle);
    m_tcpSocketList.append(pTcpSocket);
    connect(pTcpSocket, &MyTcpSocket::offline, this, &MyTcpServer::removeSocket);
}

void MyTcpServer::resend(char *tarName, PDU *pdu)
{
    qDebug() << "查找转发目标:" << tarName;
    foreach(MyTcpSocket* pTcpSocket, m_tcpSocketList)
    {
        if(pTcpSocket->m_strLoginName == tarName)
        {
            pTcpSocket->write((char*)pdu, pdu->uiPDULen);
            qDebug() << "转发消息->"
                     << "消息类型:" << pdu->uiMsgType
                     << "PDU长度:" << pdu->uiPDULen
                     << "消息长度:" << pdu->uiMsgLen
                     << "PDU数据1:" << pdu->caData
                     << "PDU数据2:" << pdu->caData + 32
                     << "消息内容:" << pdu->caMsg;
            return;
        }
    }
    qDebug() << "未找到目标:" << tarName;
}

void MyTcpServer::removeSocket(MyTcpSocket *mysocket)
{
    m_tcpSocketList.removeOne(mysocket);
    mysocket->deleteLater();
    mysocket = NULL;

    // 测试
    qDebug() << m_tcpSocketList.size();
    for(int i = 0; i < m_tcpSocketList.size(); i++)
    {
        qDebug() << m_tcpSocketList.at(i)->m_strLoginName;
    }
}

MyTcpServer::MyTcpServer()
{

}
